﻿using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace BuiltInLoggingProvider.Controllers
{
    /// <summary>
    /// 天气预报控制器
    /// </summary>
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="logger"></param>
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 获取天气
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

        /// <summary>
        /// 获取日志输出 - 通用主机
        /// </summary>
        [HttpGet]
        public void GetLogOutUniversalHost()
        {
            // 内置日志
            _logger.LogTrace(1000, "log Trace msg");
            _logger.LogDebug(1001, "log Debug msg");
            _logger.LogInformation(1002, "log Information msg");
            _logger.LogWarning(1003, "log Warning msg");
            _logger.LogError(1004, "log Error msg");
            _logger.LogCritical(1005, "log Critical msg");
        }

        /// <summary>
        /// 获取日志输出 - 非主机
        /// </summary>
        [HttpGet]
        public void GetLogOutNonHost()
        {
            var loggerFactory = LoggerFactory.Create(builder => 
            {
                builder
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
                .AddConsole()
                .AddEventLog();
            });
            ILogger logger = loggerFactory.CreateLogger<Program>();
            logger.LogInformation("非主机模式输出log msg");
        }

        /// <summary>
        /// 获取日志输出 - 第三方框架：Log4Net（简单配置，输出至控制台）
        /// </summary>
        [HttpGet]
        public void GetLogOutWithLog4NetSimpleConfiguration()
        {
            ILoggerRepository repository = LogManager.CreateRepository(".NET Core RepositoryRepository");
            // 默认简单配置，输出至控制台
            BasicConfigurator.Configure(repository);
            ILog log = LogManager.GetLogger(repository.Name, ".NET Core Log4net");

            log.Info(".NET Core Log4net log");
            log.Info("test log");
            log.Error("error");
            log.Info("linezero");
        }

        /// <summary>
        /// 获取日志输出 - 第三方框架：Log4Net（增加配置，输出至文件）
        /// </summary>
        [HttpGet]
        public void GetLogOutWithLog4NetComplexConfigurations()
        {
            ILoggerRepository repository = LogManager.CreateRepository(".NET Core RepositoryRepository");
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            ILog log = LogManager.GetLogger(repository.Name, ".NET Core Log4net");

            log.Info(".NET Core Log4net log");
            log.Info("test log");
            log.Error("error");
            log.Info("linezero");
        }

        /// <summary>
        /// 获取日志输出 - 第三方框架：NLog
        /// </summary>
        [HttpGet]
        public void GetLogOutWithNLog()
        {
            // 内置日志
            _logger.LogTrace(1000, "log Trace msg");
            _logger.LogDebug(1001, "log Debug msg");
            _logger.LogInformation(1002, "log Information msg");
            _logger.LogWarning(1003, "log Warning msg");
            _logger.LogError(1004, "log Error msg");
            _logger.LogCritical(1005, "log Critical msg");
        }

        /// <summary>
        /// 获取日志输出 - 第三方框架：Serilog
        /// </summary>
        [HttpGet]
        public void GetLogOutWithSerilog()
        {
            // 内置日志
            _logger.LogTrace(1000, "log Trace msg");
            _logger.LogDebug(1001, "log Debug msg");
            _logger.LogInformation(1002, "log Information msg");
            _logger.LogWarning(1003, "log Warning msg");
            _logger.LogError(1004, "log Error msg");
            _logger.LogCritical(1005, "log Critical msg");
        }
    }
}
